package com.ort.ezcalendar;

import group.pals.android.lib.ui.filechooser.FileChooserActivity;
import group.pals.android.lib.ui.filechooser.io.localfile.LocalFile;
import group.pals.android.lib.ui.filechooser.services.IFileProvider;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Parcelable;
import android.provider.MediaStore;
import android.text.format.Time;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TimePicker;

import com.markupartist.android.widget.ActionBar;
import com.ort.ezcalendar.mapa.MapaActivity;
import com.ort.ezcalendar.mapa.MapaSeleccionarLocActivity;
import com.ort.ezcalendar.menu.AboutActivity;
import com.ort.ezcalendar.menu.ConfigurationActivity;
import com.ort.ezcalendar.menu.HelpActivity;
import com.ort.ezcalendar.notificaciones.ManejadorAlarmas;
import com.ort.ezcalendar.persistance.EventHelper;

public class NewEventActivity extends Activity {

	private EventHelper helper;

	private EditText name, place, description, txtDate, txtHour;
	private Spinner category;
	private Calendar date;
	private Button save;
	private File rutaImagen;
	private ImageView imgView;

	private SimpleDateFormat dfFecha;
	private SimpleDateFormat dfHora;
	private Context contexto;

	// Solo para editar
	private int idEvento;
	private boolean editando;

	private static final int _ReqChooseFile = 0;
	private static final int CAMERA_PIC_REQUEST = 1337;
	static final int DATE_SELECTION_DIALOG_ID = 1;
	static final int HOUR_SELECTION_DIALOG_ID = 2;
	static final int PHOTO_SELECTION_DIALOG_ID = 3;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_new_event);
		contexto = this;
		ActionBar actionBar = (ActionBar) findViewById(R.id.actionbar);
		actionBar.setHomeLogo(R.drawable.logo_blanco);

		helper = new EventHelper(this);
		dfFecha = new SimpleDateFormat("dd/MM/yyyy");
		dfHora = new SimpleDateFormat("HH:mm");

		name = (EditText) findViewById(R.id.event_name);
		place = (EditText) findViewById(R.id.place);
		description = (EditText) findViewById(R.id.description);
		category = (Spinner) findViewById(R.id.category_value);
		txtDate = (EditText) findViewById(R.id.txtFecha);
		txtHour = (EditText) findViewById(R.id.txtHora);
		imgView = (ImageView) findViewById(R.id.imgView);

		save = (Button) findViewById(R.id.save);

		if (getIntent().getExtras() != null) {
			idEvento = getIntent().getExtras().getInt("id");
			editando = true;
			setValues();
		} else {
			resetValues();
		}
		initComboCategory();

		initEvents();
	}

	private void setValues() {
		Cursor curEvento = helper.getEvento(idEvento);
		if (curEvento.moveToFirst()) {
			name.setText(helper.getName(curEvento));
			place.setText(helper.getPlace(curEvento));
			description.setText(helper.getDescription(curEvento));
			date = Calendar.getInstance();
			date.setTime(helper.getDate(curEvento));
			SimpleDateFormat dfFecha = new SimpleDateFormat("dd/MM/yyyy");
			Sistema.getInstance().setCoordenadas(helper.getLatitude(curEvento),
					helper.getLongitude(curEvento));
			if (rutaImagen != null) {
				rutaImagen = new File(helper.getPhoto(curEvento));
				imgView.setImageDrawable(Drawable.createFromPath(rutaImagen
						.getAbsolutePath()));
			}
			txtDate.setText(dfFecha.format(date.getTime()));
			txtHour.setText(dfHora.format(date.getTime()));
			Sistema.getInstance().resetValues();
		}
		curEvento.close();
	}

	private void resetValues() {
		name.setText("");
		place.setText("");
		description.setText("");
		date = Calendar.getInstance();
		initDateView();
		initHourView();
		Sistema.getInstance().resetValues();
	}

	private void initDateView() {
		txtDate.setText(dfFecha.format(date.getTime()));
	}

	private void initHourView() {
		txtHour.setText(dfHora.format(date.getTime()));
	}

	private void initComboCategory() {
		ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
				this, R.array.categories_array,
				android.R.layout.simple_spinner_item);
		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		category.setAdapter(adapter);
	}

	private void initEvents() {
		save.setOnClickListener(onClickSave);

		txtDate.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				showDialog(DATE_SELECTION_DIALOG_ID);
			}
		});

		txtHour.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				showDialog(HOUR_SELECTION_DIALOG_ID);
			}
		});
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.activity_new_event, menu);
		return true;
	}

	private View.OnClickListener onClickSave = new View.OnClickListener() {
		public void onClick(View v) {
			if (validateFields()) {
				String ruta;
				if (rutaImagen == null)
					ruta = null;
				else
					ruta = rutaImagen.getAbsolutePath();
				long idEvent;
				if (!editando) {
					idEvent = helper.insertNewEvent(name.getText().toString(),
							place.getText().toString(), date.getTime(),
							description.getText().toString(), category
									.getSelectedItem().toString(), ruta, true,
							Sistema.getInstance().getLatitud(), Sistema
									.getInstance().getLongitud());
				} else {
					helper.editEvent(idEvento, name.getText().toString(), place
							.getText().toString(), date.getTime(), description
							.getText().toString(), category.getSelectedItem()
							.toString(), ruta, true, Sistema.getInstance()
							.getLatitud(), Sistema.getInstance().getLongitud());
					idEvent = idEvento;
				}
				ManejadorAlarmas ma = new ManejadorAlarmas(contexto);
				for (Date d : Sistema.getInstance().getAlarmListNew()) {
					helper.insertNewAlarm(idEvent, d);
					ma.agregarAlarma(d, idEvent);
				}
				showAlertDialog("El evento " + name.getText().toString()
						+ " ha sido ingresado con exito.",
						"Nuevo evento ingresado.");
				resetValues();

			} else {
				showAlertDialog(
						"Campo vacio, por favor verifique los lugares.",
						"Campo no ingresado.");
			}
		}
	};

	private void showAlertDialog(String message, String title) {
		AlertDialog.Builder dialogMessage = new AlertDialog.Builder(this);
		dialogMessage.setTitle(title);
		dialogMessage.setMessage(message);
		dialogMessage.setPositiveButton("Aceptar", null);
		dialogMessage.create();
		dialogMessage.show();
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		Intent i;
		switch (item.getItemId()) {
		case R.id.about:
			i = new Intent(this, AboutActivity.class);
			startActivity(i);
			break;
		case R.id.help:
			i = new Intent(this, HelpActivity.class);
			startActivity(i);
			break;
		case R.id.configuration:
			i = new Intent(this, ConfigurationActivity.class);
			startActivity(i);
			break;
		}
		return true;
	}

	@Override
	protected Dialog onCreateDialog(int idDialog) {
		switch (idDialog) {
		case DATE_SELECTION_DIALOG_ID:
			return new DatePickerDialog(this, datePickerListener,
					date.get(Calendar.YEAR), date.get(Calendar.MONTH),
					date.get(Calendar.DAY_OF_MONTH));
		case HOUR_SELECTION_DIALOG_ID:
			return new TimePickerDialog(this, hourPickerListener,
					date.get(Calendar.HOUR_OF_DAY), date.get(Calendar.MINUTE),
					true);
		case PHOTO_SELECTION_DIALOG_ID:
			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setTitle(R.string.select_photo_option);
			builder.setItems(R.array.options_photo_array, selectOptionPhoto);
			return builder.create();
		}
		return null;
	}

	private DialogInterface.OnClickListener selectOptionPhoto = new DialogInterface.OnClickListener() {

		public void onClick(DialogInterface dialog, int which) {
			switch (which) {
			case 0:
				tomarFoto();
				break;
			case 1:
				showChooserDialog();
				break;

			}
		}
	};

	private void tomarFoto() {
		rutaImagen = obtenerRuta();
		Uri outputFileUri = Uri.fromFile(rutaImagen);

		Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
		intent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);

		startActivityForResult(intent, CAMERA_PIC_REQUEST);
	}

	private File obtenerRuta() {
		File sdDir = Environment
				.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
		File ruta = new File(sdDir, "ezCalendar");
		ruta.mkdirs();
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyymmddhhmmss");
		String date = dateFormat.format(new Date());
		String nombreArchivo = "Picture_" + date + ".jpg";
		return new File(sdDir, "ezCalendar/" + nombreArchivo);
	}

	private void showChooserDialog() {
		Intent intent = new Intent(this, FileChooserActivity.class);
		intent.putExtra(FileChooserActivity._Rootpath,
				(Parcelable) new LocalFile("/your/path"));
		intent.putExtra(FileChooserActivity._RegexFilenameFilter,
				"(?si).*\\.(jpg|gif|png)$");
		startActivityForResult(intent, _ReqChooseFile);
	}

	private DatePickerDialog.OnDateSetListener datePickerListener = new DatePickerDialog.OnDateSetListener() {

		// when dialog box is closed, below method will be called.
		public void onDateSet(DatePicker view, int selectedYear,
				int selectedMonth, int selectedDay) {
			date.set(Calendar.YEAR, selectedYear);
			date.set(Calendar.MONTH, selectedMonth);
			date.set(Calendar.DAY_OF_MONTH, selectedDay);

			// set selected date into txtDate

			txtDate.setText(dfFecha.format(date.getTime()));
		}
	};

	private TimePickerDialog.OnTimeSetListener hourPickerListener = new TimePickerDialog.OnTimeSetListener() {
		public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
			date.set(Calendar.HOUR_OF_DAY, hourOfDay);
			date.set(Calendar.MINUTE, minute);

			txtHour.setText(dfHora.format(date.getTime()));
		}
	};

	private boolean validateFields() {
		if (name.getText().length() == 0) {
			return false;
		}
		if (place.getText().length() == 0) {
			return false;
		}
		if (category.getSelectedItem() == null) {
			return false;
		}
		if (txtDate.getText().length() == 0) {
			return false;
		}
		if (txtHour.getText().length() == 0) {
			return false;
		}
		return true;
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		switch (requestCode) {
		case _ReqChooseFile:
			if (resultCode == RESULT_OK) {
				/*
				 * you can use two flags included in data
				 */
				IFileProvider.FilterMode filterMode = (IFileProvider.FilterMode) data
						.getSerializableExtra(FileChooserActivity._FilterMode);
				boolean saveDialog = data.getBooleanExtra(
						FileChooserActivity._SaveDialog, false);

				/*
				 * a list of files will always return, if selection mode is
				 * single, the list contains one file
				 */
				List<LocalFile> files = (List<LocalFile>) data
						.getSerializableExtra(FileChooserActivity._Results);
				for (LocalFile f : files)
					rutaImagen = f;
				imgView.setImageDrawable(Drawable.createFromPath(rutaImagen
						.getAbsolutePath()));
			}
			break;
		case CAMERA_PIC_REQUEST:
			imgView.setImageDrawable(Drawable.createFromPath(rutaImagen
					.getAbsolutePath()));
			break;
		}
	}

	public void onClickSearchPhoto(View v) {
		showDialog(PHOTO_SELECTION_DIALOG_ID);
	}

	public void onClickAlarms(View v) {
		final Intent i = new Intent(this, AlarmListActivity.class);
		startActivity(i);
	}

	public void onClickLocalizacion(View v) {
		final Intent i = new Intent(this, MapaSeleccionarLocActivity.class);
		startActivity(i);
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		helper.close();
	}
}
